package jpb.test.subprocess;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Sub-process that reads an output provider class name from a file in the class path,
 * instantiates the provider and uses to deliver this sub-process output.
 *
 * @since v4.3
 */
public class OutputPrintingSubprocess {

    private static final String OUTPUT_PROVIDER_CLASS_FILE_NAME = "outputProviderClassName.info";


    public static void main(String[] args) {
        System.out.print(createOutputProviderFromFile().processOutput());
    }

    private static ProcessOutputProvider createOutputProviderFromFile() {
        try {
            Class<? extends ProcessOutputProvider> providerClass = readProviderClass();
            return providerClass.getConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private static Class<? extends ProcessOutputProvider> readProviderClass() throws Exception {
        String className = readFileToString(outputProviderClassFile()).trim();
        return (Class<? extends ProcessOutputProvider>) Class.forName(className);
    }

    public static File outputProviderClassFile() {
        return new File(System.getProperty("java.io.tmpdir") + File.separator + OUTPUT_PROVIDER_CLASS_FILE_NAME);
    }

    private static String readFileToString(File file) throws IOException
    {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder contentCollector = new StringBuilder((int) file.length() / 8);
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                contentCollector.append(line);
            }
        } finally {
            close(reader);
        }
        return contentCollector.toString();
    }


    private static void close(BufferedReader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }
}
